/**
 * 
 */
package com.alphasystem.commerce.common.annotation.apt;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import com.alphasystem.commerce.ui.cmc.ComponentType;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * @author sali
 * 
 */
public class FreemarkerPersistenceHelperImpl implements PersistenceHelper {

	private Reader reader;

	public FreemarkerPersistenceHelperImpl(File inFile)
			throws FileNotFoundException {
		reader = new BufferedReader(new FileReader(inFile));
	}

	public FreemarkerPersistenceHelperImpl(Reader reader) {
		this.reader = reader;
	}

	public void saveAsXml(File outFile, Map<String, ComponentType> components) {
		Configuration cfg = new Configuration();
		BufferedWriter writer = null;
		try {
			Template tpl = new Template("uiConfiguration", reader, cfg);
			writer = new BufferedWriter(new FileWriter(outFile));
			Map<String, Map<String, ComponentType>> map = new HashMap<String, Map<String, ComponentType>>();
			map.put("components", components);
			tpl.process(map, writer);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
				}
			}
		}
	}

}
